package org.example.project.bookstore.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.bean.Order;
import org.example.bean.OrderItem;
import org.example.config.JwtConfig;
import org.example.handler.OrderSaveException;
import org.example.mapper.OrderItemMapper;
import org.example.mapper.OrderMapper;
import org.example.project.bookstore.service.OrderService;
import org.example.util.JsonResult;
import org.example.util.NumericUUIDGenerator;
import org.example.util.ResultTool;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

/**
 * @Auther:Liu
 * @Testname:OrderServiceImpl
 * @Date:2025/8/26 09:44
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
   @Resource
   private OrderMapper orderMapper;
   @Resource
   private OrderItemMapper orderItemMapper;


    @Transactional(rollbackFor = {SQLException.class,OrderSaveException.class})
    public JsonResult saveOrrder(Order order, HttpServletRequest request) {
       //UUID生成订单ID
        long uuid = NumericUUIDGenerator.getNumericUUID();
        //设置订单ID,状态,UserId
        order.setId(uuid+"");
        order.setStatus(1);

        //获取userId
        String token = request.getHeader("token");
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        order.setUserId(userId);
        int insert = orderMapper.insert(order);
        if (insert == 0) {
            throw new OrderSaveException("订单添加失败");
        }
        List<OrderItem> orderItems = order.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getId());
            int insert1 = orderItemMapper.insert(orderItem);
            if (insert1 == 0) {
                throw new OrderSaveException("订单添加失败");
            }
        }
        return ResultTool.success(uuid+"");
    }
}
